<?php

if (!session_id()) {
    session_start();
}
$user_id = $_SESSION['user_id'];

$upload = wp_upload_dir();
if (isset($_POST['imgBase64'])) {
    $img_name = $user_id . "_" . time() . ".png";
    $img = str_replace('data:image/png;base64,', '', $_POST['imgBase64']);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = $upload['path'] . "/" . $img_name;
    $success = file_put_contents($file, $data);


    global $wpdb;
    $tb = 'ap_painting_exam';
    $imgurl = $upload['url'] . "/" . $img_name;
    $existuser = $wpdb->get_row("SELECT * FROM $tb WHERE user_id = $user_id");
   /* if ($existuser && $existuser->id) {
        $data = array('url' => $imgurl, 'dateadd' => time());
        $wpdb->update($tb, $data, array('user_id' => $user_id));
    } else { */
	if(count($existuser) < 5){
        $data = array('user_id' => $user_id, 'url' => $imgurl, 'dateadd' => time());
        $wpdb->insert($tb, $data);
    }
    echo $imgurl;
    die;
}
